import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { Skeleton, Button, message } from 'antd';
import { ArrowLeftOutlined, HeartOutlined, MessageOutlined, HeartFilled } from '@ant-design/icons';
import { Viewer } from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';
import 'github-markdown-css/github-markdown.css';
import 'highlight.js/styles/github.css';
import Header from "../../components/Header/Header.tsx";
import { getPostById } from '../../api/communityPostController';
import { getLikeStatus, likeAction } from '../../api/communityPostLikeController';
import { CommunityPostVO } from '../../types/community';
import { RootState } from '../../store';
import Comments from '../../components/Comments';

const plugins = [
  gfm(),
];

const CommunityDetail: React.FC = () => {
  const { postId } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [post, setPost] = useState<CommunityPostVO | null>(null);
  const [isLiked, setIsLiked] = useState(false);
  const loginUser = useSelector((state: RootState) => state.loginUser);

  // 获取点赞状态的函数
  const getLikeStatusFromServer = async (postId: string) => {
    try {
      if (loginUser.id) {
        const response = await getLikeStatus({ postId: Number(postId) });
        if (response.code === 200) {
          setIsLiked(response.data);
        }
      }
    } catch (error) {
      console.error('Failed to get like status:', error);
    }
  };

  // 获取帖子详情的函数
  const getPostDetailFromServer = async (postId: string) => {
    try {
      const response = await getPostById({ id: Number(postId) });
      if (response.code === 200 && response.data) {
        setPost(response.data);
      }
    } catch (error) {
      console.error('Failed to get post detail:', error);
    }
  };

  // 刷新所有状态
  const refreshAllStatus = async (postId: string) => {
    await Promise.all([
      getLikeStatusFromServer(postId),
      getPostDetailFromServer(postId)
    ]);
  };

  useEffect(() => {
    const loadPostDetail = async () => {
      if (!postId) return;
      
      try {
        setLoading(true);
        await refreshAllStatus(postId);
      } catch (error) {
        console.error('Failed to load post detail:', error);
      } finally {
        setLoading(false);
      }
    };

    loadPostDetail();
  }, [postId, loginUser.id]);

  const handleBack = () => {
    navigate(-1);
  };

  const handleLike = async () => {
    if (!post || !loginUser.id) return;
    
    try {
      const response = await likeAction({
        postId: Number(post.id),
        liked: !isLiked
      });

      if (response.code === 200) {
        message.success(!isLiked ? '点赞成功' : '已取消点赞');
        // 重新获取帖子详情
        await getPostDetailFromServer(post.id);
        
        // 获取最新的点赞状态
        const likeStatusRes = await getLikeStatus({ postId: Number(post.id) });
        if (likeStatusRes.code === 200) {
          setIsLiked(likeStatusRes.data);
        }
      }
    } catch (error) {
      message.error('操作失败，请稍后重试');
      console.error('Failed to update like status:', error);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex flex-col bg-gray-50">
        <Header />
        <div className="flex-1">
          <div className="max-w-4xl mx-auto px-4 py-6">
            <Skeleton active paragraph={{ rows: 12 }} />
          </div>
        </div>
      </div>
    );
  }

  if (!post) {
    return (
      <div className="min-h-screen flex flex-col bg-gray-50">
        <Header />
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <h2 className="text-xl text-gray-600 mb-4">帖子不存在或已被删除</h2>
            <Button type="primary" onClick={handleBack}>返回上一页</Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col bg-gray-50">
      <Header />
      <div className="flex-1">
        <div className="max-w-[1400px] mx-auto px-4 py-6">
          <div className="w-full">
            <div className="bg-white rounded-lg shadow-sm p-6">
              <div className="flex items-center space-x-4 mb-6">
                <img 
                  src={post.userVo.avatarUrl} 
                  alt={post.userVo.nickName}
                  className="w-12 h-12 rounded-full object-cover"
                />
                <div>
                  <h3 className="font-medium text-gray-900">{post.userVo.nickName}</h3>
                  <p className="text-sm text-gray-500">
                    {new Date(post.createtime).toLocaleString()}
                  </p>
                </div>
              </div>

              <h1 className="text-2xl font-bold text-gray-900 mb-4">{post.title}</h1>

              <div className="markdown-body">
                <Viewer 
                  value={post.content}
                  plugins={plugins}
                />
              </div>

              <div className="flex items-center justify-between text-gray-500 border-t pt-4 mt-6">
                <div className="flex items-center space-x-6">
                  <button 
                    onClick={handleLike}
                    className={`flex items-center hover:text-red-500 transition-colors ${
                      isLiked ? 'text-red-500' : 'text-gray-500'
                    } ${!loginUser.id ? 'cursor-not-allowed opacity-50' : ''}`}
                    disabled={!loginUser.id}
                  >
                    {isLiked ? <HeartFilled className="mr-2" /> : <HeartOutlined className="mr-2" />}
                    {post.likecount} 喜欢
                  </button>
                  <span className="flex items-center">
                    <MessageOutlined className="mr-2" />
                    {post.commentcount} 评论
                  </span>
                </div>
              </div>
            </div>

            {/* 评论区域 */}
            <Comments 
              targetId={Number(postId)} 
              targetType={1}
              currentUserId={loginUser.id}
              defaultAvatar={loginUser.avatarUrl || '/path/to/default/avatar.png'}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default CommunityDetail; 